import { BrowserRouter, Routes, Route, useNavigate, usenav, Outlet, Link, NavLink } from "react-router-dom"
import { useLocation, useMatch } from "react-router"
import { SettingOutlined, MenuFoldOutlined, MenuUnfoldOutlined } from "@ant-design/icons";
import { Layout, Menu, ConfigProvider, Breadcrumb } from "antd";
import take from "lodash/take"
import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
import "./index.css";
import logoImg from "../../images/logo.png";
import zhCN from "antd/es/locale/zh_CN";
import { Tenant } from "./Tenant";//租户管理
import TenantDetail from "./Tenant/TenantDetail";
import { AppManage } from './AppManage';
import AppBind from './AppBind'//超级APP
import { useSubscribe } from "../../framework/common/eventBus";
import { useUpdate } from "ahooks";
import request from "../../framework/common/utils/request";

const { Header, Content, Sider } = Layout;

const items = [
  {
    key: `application`,
    icon: React.createElement(SettingOutlined),
    label: `应用管理`,
    component: <AppManage></AppManage>,
    path: "/platform-manage/application"
  },
  {
    key: `tenant`,
    icon: React.createElement(SettingOutlined),
    label: `租户管理`,
    component: <Tenant></Tenant>,
    path: "/platform-manage/tenant",
    children: [
      {
        key: `tenant-detail`,
        label: `租户详情`,
        component: <TenantDetail></TenantDetail>,
        hide: true,//不展示在菜单上，但是需要生成路由
        path: "/platform-manage/tenant/detail",
      },
    ],
  },
  {
    key: `setting`,
    icon: React.createElement(SettingOutlined),
    label: `系统管理`,
    path: "/platform-manage/setting",
    component: <AppBind></AppBind>,
    children: [
      {
        key: `app-bind`,
        label: `移动绑定`,
        component: <AppBind></AppBind>,
        path: "/platform-manage/setting/app-bind"
      },
    ],
  },
];

let routeItems = [];
//设置路由需要的参数
function setRoute({
  menus
}) {
  menus.forEach(function (menu) {
    let item = {
      key: menu.key,
      path: menu.path,
      label: menu.label,
      component: menu.component
    };
    routeItems.push(item);
    if (menu.children) {
      setRoute({
        menus: menu.children
      })
    }
  })
}
setRoute({
  menus: items
});

//生成左侧菜单需要的数据结构
function getMenusItems({
  menus
}) {
  return menus.filter(function (menu) {
    if (menu.hide !== true) {//菜单没配置隐藏才放进需要的数据结构
      if (menu.children) {//存在子节点时，对子节点也进行过滤
        menu.children = getMenusItems({
          menus: menu.children
        })
        if (menu.children.length <= 0) {//子节点过滤后，如果为空数组，需要删掉children属性
          delete menu.children;
        }
      }
      return menu;
    } else {
      return false
    }
  })
}
let menusItems = getMenusItems({
  menus: items
});

//根据菜单配置，生成Route对象
function getRoute({
  menus
}) {
  if (!menus) {
    return null;
  }
  return menus.map(function (menu) {
    let component = menu?.component || null;//菜单配置的对应组件
    return <Route
      key={menu.key}
      path={menu.path}
      element={component}
      aaa={menu.key}
    >
      {
        getRoute({ menus: menu.children })
      }
    </Route>
  });
}

//面包屑
function GetBreadcrumb({
  path
}) {
  if (!path) {
    return null;
  }

  let pathKey = path.split("/")
  return <Breadcrumb
    className="inline-block mysoft-breadcrumb"
    separator=">"
  >
    {
      pathKey.map(function (item, index) {
        if (index <= 1) {//前两个索引不生成面包屑
          return null;
        }
        let url = take(pathKey, index + 1).join("/");
        let menu = routeItems.find(function (menuItem) {
          if (menuItem.path == url) {
            return menuItem
          }
        })
        if (!menu) {
          return;
        }
        if (index === pathKey.length - 1) {//如果是最后一个，面包屑不要带连接
          document.title = menu.label;
          return <Breadcrumb.Item key="home">
            {menu.label}
          </Breadcrumb.Item>
        } else {//其他的面包屑需要带链接
          return <Breadcrumb.Item key="home">
            <Link to={url}>{menu.label}</Link>
          </Breadcrumb.Item>
        }
      })
    }
  </Breadcrumb>
}

const App = () => {
  let { pathname } = useLocation();//当前路由地址
  let pathKey = pathname.split("/");
  pathKey = pathKey[2];//按照路由规则，第二个参数是menu对应的key

  let selectedKeys = [pathKey];//当前选中的菜单key
  let defaultSelectedKeys = [items[0].key];//默认选中菜单的第一个key

  const navigate = useNavigate();
  const [collapsed, setCollapsed] = useState(false);

  let update = useUpdate();
  let userInfo = useRef({
    userInfo: {
      userName: ""//用户名称
    },
    // appName: "产业建管-华为云",
    // appVersion: "43.11-31"
    appName: "",
    appVersion: ""
  })

  useEffect(function () {
    request({
      url: "/platform/site/env-info",//获取用户信息
      method: "get"
    }).then(function (response) {
      if (response?.code === 1) {
        userInfo.current = response.data;
        // userInfo.current = {
        //   userInfo: {
        //     userName: "系统管理员"//用户名称
        //   },
        //   appName: "产业建管-华为云",
        //   appVersion: "43.11-31"
        // }//测试数据
        update();
      }
    });
  }, [])

  return (
    <ConfigProvider locale={zhCN}>
      <Layout className="h-screen">
        <Header className="text-white header">
          <img width="145" height="43" src={logoImg} alt="" className="align-middle -mt-[3px]" />
          {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
            className: " px-6 text-lg leading-[64px] cursor-pointer hover:text-[#1890ff] align-middle relative top-[2px]",
            onClick: () => setCollapsed(!collapsed),
          })}

          {/* 面包屑 */}
          <GetBreadcrumb path={pathname}></GetBreadcrumb>

          <div className=" float-right">
            <div className="menu-submenu">
              <span className="mr-3">{userInfo.current.appName}</span>
              <span>{userInfo.current.appVersion}</span>
            </div>
            <UserAvatar appInfo={userInfo.current}></UserAvatar>
          </div>

        </Header>
        <Layout>

          <Sider width={160} collapsedWidth={52} trigger={null} collapsible collapsed={collapsed} className="">
            <Menu
              mode="inline"
              defaultSelectedKeys={defaultSelectedKeys}
              selectedKeys={selectedKeys}
              defaultOpenKeys={["setting"]}
              style={{
                height: "100%",
                borderRight: 0,
              }}
              items={menusItems}
              onClick={({ item, key, keyPath, domEvent }) => {
                let path = item.props.path;
                navigate(path);
              }}
            />
          </Sider>

          <Layout
            style={{
              // padding: "0 24px 24px",
            }}
          >
            <Content
              className="m-3"
              style={{
                minHeight: 280,
              }}
            >
              <Outlet />
            </Content>
          </Layout>
        </Layout>
      </Layout>
    </ConfigProvider>
  );
};

//用户头像信息
function UserAvatar({
  appInfo
}) {
  return <div className="menu-submenu ">
    <div className="ivu-menu-submenu-title">
      <span className="titleName" title={appInfo.userInfo.userName}>{appInfo.userInfo.userName.slice(0, 2)}</span>
      <img className="indexla hidden" src="/public/imgs/indexla.png" alt="" width={10} />
    </div>
    {
      false &&
      <div className="select-dropdown">
        <ul className="menu-drop-list">
          <li className="user-item">
            <div className="titleName" title={appInfo.userInfo.userName}>{appInfo.userInfo.userName.slice(0, 2)}</div>
            <div className="userName">
              <p className="name" title={appInfo.userInfo.userName}>{appInfo.userInfo.userName}</p>
              <p className="org" title={appInfo.userInfo.userOrg}>{appInfo.userInfo.userOrg}</p>
            </div>
          </li>
          <li className="menu-item logout hidden">
            <i className="icon-tuichudenglu"></i>
            <span>退出</span>
          </li>
        </ul>
      </div>
    }
  </div>
}

export default function () {
  return <BrowserRouter>
    <Routes>
      <Route key="main" path='/' element={<App />}>
        {
          getRoute({ menus: routeItems })
        }
      </Route>
    </Routes>
  </BrowserRouter>
};

